<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Controller;

use Hyperf\View\RenderInterface;

class IndexController extends AbstractController
{
    public function index(RenderInterface $render)
    {
        /*$user = $this->request->input('user', 'Hyperf');
        $method = $this->request->getMethod();

        return [
            'method' => $method,
            'message' => "Hello {$user}.",
        ];*/

        return $render->render('index', ['url' => 'ws://192.168.99.100:9502']);
    }

    public function clear()
    {
        $redis = redis();
        $redis->del('room:search:lock');
        $roomService = container()->get(\App\Game\Service\RoomService::class);
        $userService = container()->get(\App\Game\Service\UserService::class);

        $room_list = [];
        $idle_list = $redis->smembers(config('game.key.idle_room'));
        $busy_list = $redis->smembers(config('game.key.busy_room'));
        foreach($idle_list as $_id) {
            $room_list[] = $roomService->findRoom(intval($_id))->toArray();
        }
        foreach($busy_list as $_id) {
            $room_list[] = $roomService->findRoom(intval($_id))->toArray();
        }
        
        $user_list = [];
        $uid_list = $redis->smembers(config('game.key.user_list'));
        $user_list = $userService->findUsers($uid_list);

        $clear = $this->request->input('clear');
        if ($clear) {
            $roomService->clear();
            $userService->clear();
        }
        //$roomService->clear();
        return [
            'idle' => $roomService->idle_count(),
            'busy' => $roomService->busy_count(),
            'users' => $userService->count(),
            'rooms' => $room_list,
            'user_list' => $user_list->map(function($u){ return $u->toArray(); })->toArray(),
        ];
    }
}
